import { defineStore } from "pinia";
import staffPreset from "@/profiles/staffs.json";
import dayjs from "dayjs";

const usePlanningStore = defineStore("planningStore", () => {
  // ==============================================================
  // StepView 相关内容
  // ==============================================================

  // 当前步骤
  const currentStep = ref(1);

  // ==============================================================
  // TimeSlotView 相关内容
  // ==============================================================

  // 预计排班时段及粒度
  const timeRanges = ref([]);

  // 生成的排班计划 --> 输出
  const timeSlots = ref([]);

  // 排班自然日 --> 输出
  const planningDates = computed(() => {
    if (timeRanges.value.length === 0) {
      return [];
    }
    let startDay = null;
    let endDay = null;
    for (let range of timeRanges.value) {
      let startDateString = `${range.startDate} ${range.startTime}`;
      let endDateString = `${range.endDate} ${range.endTime}`;
      if (!startDay) {
        startDay = dayjs(startDateString);
      } else if (startDay.isAfter(startDateString)) {
        startDay = dayjs(startDateString).startOf("day");
      }
      if (!endDay) {
        endDay = dayjs(endDateString);
      } else if (endDay.isBefore(endDateString)) {
        endDay = dayjs(endDateString);
      }
    }
    let dates = [];
    let currentDay = startDay.startOf("day");
    while (currentDay.isSameOrBefore(endDay, "day")) {
      dates.push(currentDay.format("YYYY-MM-DD"));
      currentDay = currentDay.add(1, "day");
    }
    return dates;
  });

  // ==============================================================
  // SeatSlotView 相关内容
  // ==============================================================

  // 选定的排班科室
  const selectedOrgId = ref(1);

  // 是否同步后续时段的席位勾选
  const isSeatSlotsCopyFollowings = ref(true);

  // ==============================================================
  // StaffPickerView 相关内容
  // ==============================================================

  // 选定的值班时段的值班人
  const selectedStaffIds = ref([]);
  const selectedStaffs = computed(() => {
    if (selectedStaffIds.value.length === 0) {
      return [];
    }
    return staffPreset.filter((staff) =>
      selectedStaffIds.value.includes(staff.id)
    );
  });

  // 确定的执勤人员 --> 输出
  const confirmedStaffs = ref([]);

  // ==============================================================
  // TaskSlotView 相关内容
  // ==============================================================

  return {
    timeRanges,
    planningDates,
    timeSlots,
    currentStep,
    selectedOrgId,
    isSeatSlotsCopyFollowings,
    selectedStaffIds,
    selectedStaffs,
    confirmedStaffs,
  };
});

export default usePlanningStore;
